import 'package:flutter/material.dart';
import '../models/ddl_item.dart';
import '../app_data_manager.dart';
import '../widges/ddl_detail_card.dart';
import 'memo_page.dart';

class RecycleBinPage extends StatefulWidget {
  const RecycleBinPage({super.key});

  @override
  State<RecycleBinPage> createState() => _RecycleBinPageState();
}

class _RecycleBinPageState extends State<RecycleBinPage> {
  List<DDLItem> get recycleBinItems => AppDataManager().recycleBin;
  bool _isManaging = false;
  final Set<DDLItem> _selectedItems = {};
  bool _isDragging = false;

  @override
  void initState() {
    super.initState();
    AppDataManager().init().then((_) {
      setState(() {});
    });
  }

  void _toggleManaging() {
    setState(() {
      _isManaging = !_isManaging;
      if (!_isManaging) {
        _selectedItems.clear();
      }
    });
  }

  void _toggleSelect(DDLItem item) {
    setState(() {
      if (_selectedItems.contains(item)) {
        _selectedItems.remove(item);
      } else {
        _selectedItems.add(item);
      }
    });
  }

  Future<void> _deleteSelected() async {
    if (_selectedItems.isEmpty) return;

    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要永久删除选中的 ${_selectedItems.length} 个DDL吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      for (var item in _selectedItems) {
        await AppDataManager().removeSingleFromRecycleBin(item);
      }
      setState(() {
        _selectedItems.clear();
        _isManaging = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('回收站'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        actions: [
          if (_isManaging)
            TextButton(
              onPressed: _deleteSelected,
              child: Text(
                '删除选中(${_selectedItems.length})',
                style: const TextStyle(color: Colors.red),
              ),
            ),
          TextButton(
            onPressed: () async {
              final confirmed = await showDialog<bool>(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('确认清空'),
                  content: const Text('确定要清空回收站吗？'),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.of(context).pop(false),
                      child: const Text('取消'),
                    ),
                    TextButton(
                      onPressed: () => Navigator.of(context).pop(true),
                      child: const Text('清空', style: TextStyle(color: Colors.red)),
                    ),
                  ],
                ),
              );

              if (confirmed == true) {
                await AppDataManager().clearRecycleBin();
                setState(() {});
              }
            },
            child: const Text('清空回收站'),
          ),
          IconButton(
            icon: Icon(
              _isManaging ? Icons.done : Icons.delete_outline,
              color: _isManaging ? Colors.red : Colors.black,
            ),
            onPressed: _toggleManaging,
          ),
        ],
      ),
      body: Column(
        children: [
          if (_isManaging)
            Container(
              padding: const EdgeInsets.all(8),
              color: Colors.grey[100],
              child: Row(
                children: [
                  const Icon(Icons.info_outline),
                  const SizedBox(width: 8),
                  const Expanded(
                    child: Text(
                      '点击卡片可以选中/取消选中',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ),
                ],
              ),
            ),
          if (!_isManaging && _isDragging)
            Row(
              children: [
                Expanded(
                  child: DragTarget<DDLItem>(
                    onWillAcceptWithDetails: (item) => true,
                    onAcceptWithDetails: (item) async {
                      // 使用copyWith创建新实例
                      final newItem = item.data.copyWith(
                        isUrgent: true,
                        isCompleted: false,
                        isAbandoned: false,
                      );
                      // 先添加到DDL列表
                      await AppDataManager().addToDDL(newItem);
                      // 然后从回收站移除
                      await AppDataManager().removeFromRecycleBin(item.data);
                      
                      // 更新统计数据（从回收站恢复，对应状态数量-1）
                      final now = DateTime.now();
                      final date = '${now.year}-${now.month}-${now.day}';
                      if (item.data.isCompleted) {
                        await AppDataManager().updateGoalStats(date, 'completed', -1);
                        print('从回收站恢复完成项，完成数-1');
                      } else if (item.data.isAbandoned) {
                        await AppDataManager().updateGoalStats(date, 'abandoned', -1);
                        print('从回收站恢复放弃项，放弃数-1');
                      } else {
                        await AppDataManager().updateGoalStats(date, 'cancelled', -1);
                        print('从回收站恢复取消项，取消数-1');
                      }
                      
                      setState(() {
                        _isDragging = false;
                      });
                    },
                    builder: (context, candidateData, rejectedData) {
                      final bool isTargeting = candidateData.isNotEmpty;
                      return AnimatedContainer(
                        duration: const Duration(milliseconds: 200),
                        height: 60,
                        color: isTargeting ? Colors.red[200] : Colors.red[100],
                        child: Center(
                          child: Text(
                            '急急国王',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: isTargeting ? Colors.white : Colors.black,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
                Expanded(
                  child: DragTarget<DDLItem>(
                    onWillAcceptWithDetails: (item) => true,
                    onAcceptWithDetails: (item) async {
                      // 使用copyWith创建新实例
                      final newItem = item.data.copyWith(
                        isUrgent: false,
                        isCompleted: false,
                        isAbandoned: false,
                      );
                      // 先添加到DDL列表
                      await AppDataManager().addToDDL(newItem);
                      // 然后从回收站移除
                      await AppDataManager().removeFromRecycleBin(item.data);
                      
                      // 更新统计数据（从回收站恢复，对应状态数量-1）
                      final now = DateTime.now();
                      final date = '${now.year}-${now.month}-${now.day}';
                      if (item.data.isCompleted) {
                        await AppDataManager().updateGoalStats(date, 'completed', -1);
                        print('从回收站恢复完成项，完成数-1');
                      } else if (item.data.isAbandoned) {
                        await AppDataManager().updateGoalStats(date, 'abandoned', -1);
                        print('从回收站恢复放弃项，放弃数-1');
                      } else {
                        await AppDataManager().updateGoalStats(date, 'cancelled', -1);
                        print('从回收站恢复取消项，取消数-1');
                      }
                      
                      setState(() {
                        _isDragging = false;
                      });
                    },
                    builder: (context, candidateData, rejectedData) {
                      final bool isTargeting = candidateData.isNotEmpty;
                      return AnimatedContainer(
                        duration: const Duration(milliseconds: 200),
                        height: 60,
                        color: isTargeting ? Colors.blue[200] : Colors.blue[100],
                        child: Center(
                          child: Text(
                            '你看，又急',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: isTargeting ? Colors.white : Colors.black,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          Expanded(
            child: ListView.builder(
              itemCount: recycleBinItems.length,
              itemBuilder: (context, index) {
                final item = recycleBinItems[index];
                final isSelected = _selectedItems.contains(item);
                
                return _isManaging
                    ? GestureDetector(
                        onTap: () => _toggleSelect(item),
                        child: Container(
                          decoration: BoxDecoration(
                            color: isSelected ? Colors.red.withOpacity(0.1) : null,
                            border: isSelected
                                ? Border.all(color: Colors.red, width: 2)
                                : null,
                          ),
                          child: Row(
                            children: [
                              Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Icon(
                                  isSelected ? Icons.check_circle : Icons.radio_button_unchecked,
                                  color: isSelected ? Colors.red : Colors.grey,
                                ),
                              ),
                              Expanded(
                                child: DDLDetailCard(
                                  item: item,
                                  isInRecycleBin: true,
                                  onTap: () {}, // 提供一个空函数，因为点击事件由GestureDetector处理
                                ),
                              ),
                            ],
                          ),
                        ),
                      )
                    : LongPressDraggable<DDLItem>(
                        data: item,
                        dragAnchorStrategy: childDragAnchorStrategy,
                        onDragStarted: () {
                          print('onDragStarted: $item');
                          setState(() {
                            _isDragging = true;
                          });
                        },
                        onDragCompleted: () {
                          print('onDragCompleted: $item');
                          setState(() {
                            _isDragging = false;
                          });
                        },
                        onDraggableCanceled: (velocity, offset) {
                          print('onDraggableCanceled: $item');
                          setState(() {
                            _isDragging = false;
                          });
                        },
                        feedback: Material(
                          elevation: 8,
                          borderRadius: BorderRadius.circular(8),
                          child: Container(
                            width: MediaQuery.of(context).size.width * 0.4,
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(8),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.2),
                                  blurRadius: 8,
                                  spreadRadius: 1,
                                ),
                              ],
                            ),
                            child: Text(item.title),
                          ),
                        ),
                        childWhenDragging: Opacity(
                          opacity: 0.5,
                          child: DDLDetailCard(
                            item: item,
                            isInRecycleBin: true,
                            onTap: () {},
                          ),
                        ),
                        child: DDLDetailCard(
                          item: item,
                          isInRecycleBin: true,
                          onTap: () async {
                            await AppDataManager().restoreFromRecycle(item);
                            setState(() {});
                          },
                        ),
                      );
              },
            ),
          ),
        ],
      ),
    );
  }
} 